package com.jinke.api.modules.third.ezeeship.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jinke.api.common.annotation.Apilog;
import com.jinke.api.common.util.CommonUtil;
import com.jinke.api.modules.app.request.CancelLabelRequest;
import com.jinke.api.modules.app.request.TrackingRequest;
import com.jinke.api.modules.third.ezeeship.model.request.EstimateRateRequest;
import com.jinke.api.modules.third.sjgj.model.request.BaseEntity;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
@RequiredArgsConstructor
public class EzeeShipUtil {
    //nevol.wang@foxmail.com
    public static final String TOKEN = "c9512c5bb10f11ee9ee8d3f3ba4a6320";
    public static final String ADDRESS_VALIDATE = "https://ezeeship.com/api/ezeeship-openapi/address/validate";
    public static final String LABEL_CREATE = "https://ezeeship.com/api/ezeeship-openapi/label/create";
    public static final String ESTIMATE_RATE = "https://ezeeship.com/api/ezeeship-openapi/shipment/estimateRate";
    public static final String LABEL_CANCEL = "https://ezeeship.com/api/ezeeship-openapi/label/cancel";
    public static Map<String, String> messages;

    private String sendPostRequest(String url, String requestBody) throws IOException {
        HttpURLConnection connection = null;
        try {

            // 创建连接
            URL apiUrl = new URL(url);
            if ("true".equals(System.getenv("local"))) {
                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", 10809));
                connection = (HttpURLConnection) apiUrl.openConnection(proxy);
            } else {
                connection = (HttpURLConnection) apiUrl.openConnection();
            }


            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Authorization", TOKEN);
            connection.setDoOutput(true);

            // 写入请求体
            try (OutputStream outputStream = connection.getOutputStream()) {
                outputStream.write(requestBody.getBytes("UTF-8"));
            }

            // 获取响应
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                return response.toString();
            }
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    private String sendGetRequest(String url) throws IOException {
        HttpURLConnection connection = null;
        try {
            String seq = CommonUtil.getOrderNo();
            log.info("send : {}, {}", seq, url);
            URL apiUrl = new URL(url);
            if ("true".equals(System.getenv("local"))) {
                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", 7890));
                connection = (HttpURLConnection) apiUrl.openConnection(proxy);
            } else {
                connection = (HttpURLConnection) apiUrl.openConnection();
            }

            connection.setRequestMethod("GET");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Authorization", TOKEN);

            // 获取响应
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                log.info("rec : {}, {}", seq, response.toString());
                return response.toString();
            }
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }



    @Apilog(requestTypeName = "EzeeShip-预估")
    public String estimateRate(EstimateRateRequest estimateRateRequest) {
        try {
            handelRequst(estimateRateRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Integer id = estimateRateRequest.getUserChannelVO().getChannel().getId();
        String orderNO = estimateRateRequest.getOrderNO();
        try {
            estimateRateRequest.getExtra().setSignatureOption("4");
            // 发送POST请求
            String requestBody = JSONUtil.toJsonStr(estimateRateRequest);
            log.info("EzeeShip 估价请求参数--------------->{},{},{}",id, orderNO, requestBody);
            String response = sendPostRequest(ESTIMATE_RATE, requestBody);
            // 处理响应
            log.info("EzeeShip 估价响应参数--------------->{},{}", orderNO, response);
            return response;
        } catch (Exception e) {
            log.info("EzeeShip 估价异常--------------->{}", orderNO);
            e.printStackTrace();
        }
        return Strings.EMPTY;
    }

    /**
     * 把前端传来的清单信息转到参数中
     * @param estimateRateRequest
     */
    private void handelRequst(EstimateRateRequest estimateRateRequest) {
        EstimateRateRequest.LabelExtra extra = estimateRateRequest.getExtra();
        EstimateRateRequest.CustomsDeclaration customsDeclare=new EstimateRateRequest.CustomsDeclaration();
        if (StringUtils.isBlank(extra.getEinNumber())){
            return;
        }
        //Employer Identification Number即雇主识别号码，也称为联邦税号
        estimateRateRequest.getExtra().setEinNumber(extra.getCertifySigner());
        //用途 :GIFT
        customsDeclare.setContentsType(extra.getContentsType());
        customsDeclare.setEelPfc("30.36");
        List<EstimateRateRequest.CustomsDeclaration.Item> items=new ArrayList<>();
        EstimateRateRequest.CustomsDeclaration.Item item=new EstimateRateRequest.CustomsDeclaration.Item();
        if (extra.getQuantity()==null){
            //前台没传默认数量为1
            item.setQuantity(1);
        }else {

            item.setQuantity(extra.getQuantity());
        }
        item.setQuantityUnit(extra.getQuantityUnit());
        item.setWeight(extra.getWeight());
        item.setMassUnit(extra.getWeightUnit());
        //海关申报价值
        item.setValueAmount(extra.getCustomsDeclaration());

        if (extra.getCountryOfOrigin().contains("CANADA")){
            item.setOriginCountry("CA");

        }else {
            item.setOriginCountry(extra.getCountryOfOrigin());

        }
        //private String tariffNumber;
        item.setDescription(extra.getDescription());
        if (item.getQuantityUnit().contains("ea")){
            item.setQuantityUnit("EA");
        }
        items.add(item);


        customsDeclare.setItems(items);
        estimateRateRequest.setCustomsDeclarations(customsDeclare);

        estimateRateRequest.getExtra().setEinNumber(extra.getEinNumber());

        if (estimateRateRequest.getTo().getCountryCode().contains("nada")){
            estimateRateRequest.getTo().setCountryCode("CA");
        }

        String zipCode = estimateRateRequest.getTo().getZipCode();
        String replace = zipCode.replace(" ", "");
        String replace1 = replace.replace("-", "");

        estimateRateRequest.getTo().setZipCode(replace1);
    }

    @Apilog(requestTypeName = "EzeeShip-下单")
    public String createLabel(EstimateRateRequest request) {
        try {
            handelRequst(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String orderNO = request.getOrderNO();
        try {
            request.getExtra().setSignatureOption("4");



            // 发送POST请求
            EstimateRateRequest tmp = new EstimateRateRequest();
            BeanUtil.copyProperties(request, tmp);
            tmp.setOrderNO(tmp.getPlatformNo());
            String param = JSONUtil.toJsonStr(tmp);
            log.info("=======EzeeShip下单参数========,{},{}",orderNO, param);

            String response = sendPostRequest(LABEL_CREATE, param);
            log.info("=======EzeeShip下单响应结果========,{}", response);
            // 处理响应
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Strings.EMPTY;
    }

    @Apilog(requestTypeName = "EzeeShip-取消")
    public String cancelLabel(String objectId, String orderNo) {
        try {
            // 发送POST请求
            CancelLabelRequest cancelLabelRequest = new CancelLabelRequest();
            cancelLabelRequest.setObjectId(objectId);
            String param = JSONUtil.toJsonStr(cancelLabelRequest);
            log.info("=======EzeeShip取消参数========,{},{}",orderNo, param);
            String response = sendPostRequest(LABEL_CANCEL, param);
            log.info("=======EzeeShip取消响应========{},{}",orderNo, response);
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Strings.EMPTY;
    }

    public String tracking(String trackingNumber) {

        try {
            // 发送POST请求
            TrackingRequest cancelLabelRequest = new TrackingRequest();
            cancelLabelRequest.setTrackingNumber(trackingNumber);
            String requestBody = JSONUtil.toJsonStr(cancelLabelRequest);
            String response = sendPostRequest("https://ezeeship.com/api/ezeeship-openapi/label/tracking", requestBody);
            // 处理响应
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Strings.EMPTY;
    }

    public String validateAddress(EstimateRateRequest.Address address) {

        String requestBody = JSONUtil.toJsonStr(address);
        try {
            // 发送POST请求
            log.info("---------校验地址参数---------"+requestBody);
            String response = sendPostRequest(ADDRESS_VALIDATE, requestBody);
            log.info("---------校验地址响应---------"+response);

            // 处理响应
            return response;
        } catch (Exception e) {
            log.info("---------校验地址响应---------{},{}",requestBody,e.getMessage());

        }
        return Strings.EMPTY;
    }

    public String getLabel(String objectId) {

        try {
            String response = sendGetRequest("https://ezeeship.com/api/ezeeship-openapi/label/get/" + objectId);
            // 处理响应
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Strings.EMPTY;
    }

    public String getChannel() {
        // 设置API端点URL
        String apiUrl = "https://sj.tanwapost.com/xapi/channel.php"; // 替换成实际的API URL

        // 将OrderRequest对象转换为JSON字符串
        // 创建OrderRequest对象
        BaseEntity orderRequest = new BaseEntity();

// 设置属性值
        orderRequest.setApikey("tw_4838");
        orderRequest.setApisecret("70873e8580c9900986939611618d7b1e");

        String requestBody = JSONUtil.toJsonStr(orderRequest);

        try {
            // 发送POST请求
            System.out.println();
            String response = sendPostRequest(apiUrl, requestBody);
            System.out.println("Response: " + response);
            // 处理响应
            return response;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 当三方接口返回包含设定内容替换成更合适的返回
     * @param msg
     * @return
     */
    public String fmtMsg(String msg) {
        if (StringUtils.isNotBlank(msg)) {
            for (String key : messages.keySet()) {
                if (msg.contains(key)) {
                    msg = messages.get(key);
                    break;
                }
            }
        }
        return msg;
    }

}
